import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import Tooltip from '@kuiper-components/tooltip';
import Input from '@kuiper-components/input';
import Icon from './icon';
import { Link } from 'react-router-dom';
import Table from '@knownsec/react-component/dist/Table';
import Select from '@knownsec/react-component/dist/Select';
import Button from '@knownsec/react-component/dist/Button';
import WarningsStatusEdit from '../../../../../../components/WarningsStatusEdit';
import Empty from '../../../../../../components/empty/EmptyData';
import CopyBoard from '../../../../../../components/CopyBoard';
import { datetime } from '../../../../../../../common/formatter';
import { WARNING_SECURITYEVENT_MAP } from '../../../../../../../common/constants';
import IgnoreRiskConfirm from '../../../../../../components/IgnoreRiskDialog';

import s from './style.module.css';
import { it } from 'date-fns/locale';

function warningStatsBuilder(warning = {}, modifiedAble = true) {
	let text;
	if (warning.ignoredTime) {
		text = (
			<Tooltip
				placement="top"
				overlay={
					<span className={s.time}>
						忽略操作: {datetime(warning.ignoredTime)}
					</span>
				}
			>
				<span className={s.ignored}>已忽略</span>
			</Tooltip>
		);
	} else if (warning.isResolved) {
		text = <span className={s.resolved}>已处理</span>;
	} else {
		text = <span className={s.notResolved}>待处理</span>;
	}
	return text;
}
const levelColor = {
	5: '#D5342F',
	4: '#F04038',
	3: '#F18246',
	2: '#FCD94A'
}
const levelMap = {
	5: '严重',
	4: '高危',
	3: '中危',
	2: '低危'
}
function NewTable({
	tp,
	className,
	title,
	data,
	isModified,
	cydEnabled,
	taskId,
	refetch,
	linkType,
	loading,
	notStatus,
	empty,
	id,
	jid,
	atid,
	isHistory,
	taskType,
	refresh
}) {
	const titleObj = {
		暗链: '暗链数',
		坏链: '坏链数',
		风险外链: '风险外链数',
	};
	const [filter, setFilter] = React.useState({ type: '', level: '' })
	const tableData = (data[title] || []).reduce((total, item) => {
		const detailCount = {
			keyword: 0,
			domain: 0,
			icp: 0
		}
		Object.values(item.detail).map(i => {
			Object.keys(detailCount).map(key => {
				detailCount[key] += i[key] ? i[key].length : 0
			})
			item = {...item, ...detailCount}
		})
		if (filter?.type || filter?.level) {
			if (filter?.type && filter?.level) {
				(item[filter?.type] && item.level.toString() === filter?.level) && total.push(item)
			} else {
				item[filter?.type] && total.push(item)
				item.level.toString() === filter?.level && total.push(item)
			}
		} else {
			total.push(item)
		}
		return total;
	}, []).sort((a, b) => { return Number(b.level) - Number(a.level) });
	const [colum, setColum] = React.useState([]);
	const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRowKeys(newSelectedRowKeys);
	};
	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
	};
	const nodeRef = React.useRef();
	const columns = [
		{
			title: '风险地址',
			dataIndex: 'affects',
			key: 'affects',
			width: 550,
			// eslint-disable-next-line react/display-name
			render: affects => {
				return <CopyBoard className={s.affect} text={affects} />;
			},
		},
		{
			title: '威胁等级',
			dataIndex: 'level',
			key: 'level',
			render (e) {
				return e ? <span style={{color: levelColor[e]}}>{levelMap[e]}</span> : '- -'
			}
		},
		{
			title: '操作',
			key: 'oper',
			width: 160,
			render(cur, record) {
				const url = linkType
					? `/asset-manage/manage/web/securityEvent-detail/${record.tid}/DetailP`
					: `/job-manage/web-task/securityEvent-detail/${record.tid}/DetailP`;
				return (
					<>
						<Link
							to={{
								pathname: url,
								sendState: { id: record._id, jid, atid, isHistory, taskType, taskId: record.tid, title: record.title, cydEnabled },
							}}
						>
							查看详情
						</Link>
						<IgnoreRiskConfirm className={'ml5'} data={{ task_id: record.tid, warning_ids: [record._id] }} refresh={refresh} />
					</>
				);
			},
		},
	];
	React.useEffect(() => {
		const hackLink = {
			title: '暗链数',
			key: 'hack',
			render(cur, record) {
				return <div>{linkSUM(record)}</div>;
			},
		};
		const badLink = {
			title: '坏链数',
			key: 'bad',
			render(cur, record) {
				return <div>{linkSUM(record)}</div>;
			},
		};
		const secuLink = [{
			title: '风险外链数',
			key: 'secu',
			render(cur, record) {
				return <div>{linkSUM(record)}</div>;
			},
		}, {
			title: '风险外链类型数',
			key: 'type',
			render(cur, record) {
				const detailCount = {
					keyword: 0,
					domain: 0,
					icp: 0
				}
				Object.values(record.detail).map(item => {
					Object.keys(detailCount).map(key => {
						detailCount[key] += item[key] ? item[key].length : 0
					})
				})
				return 	<Tooltip
					placement="top"
					overlay={<div className={s.typeTooltip}>
						{Object.keys(detailCount).map(key => {
							return <div>
								<p>{WARNING_SECURITYEVENT_MAP[key]}</p>
								<p>{detailCount[key]}</p>
							</div>
						})}
					</div>}
					overlayClassName={s.dropdown}>
						<div className={s.secuType}>{Object.keys(detailCount).map(key => {
							return <div className='ell' title={detailCount[key]}>{detailCount[key]}</div>
						})}</div>
				</Tooltip>;
			},
		}];
		if (titleObj.hasOwnProperty(title)) {
			let co = [...columns];
			const idx = columns.findIndex(item => item.status === 'status');
			co.splice(
				1,
				0,
				hackLink.title.includes(title)
					? hackLink
					: badLink.title.includes(title)
					? badLink
					: secuLink
			);
			co = co.flat()
			setColum(co);
		} else {
			setColum(columns);
		}
	}, [title]);

	const handleResetSelected = () => {
		setSelectedRowKeys([]);
	};
	const linkSUM = d => {
		const title = d.title;
		if (title === '暗链') {
			return d.detail.links.length;
		} else if (title === '坏链') {
			return d.detail.length;
		} else {
			const key = Object.keys(d.detail);
			return key.length;
		}
	};
	const style = { display: 'flex', 'align-items': 'center' };
	return (
		<div className={cn(className, s.tableWapper)} ref={nodeRef}>
			<div className={cn(s.title, {[s.mt15]: notStatus, [s.df_aic_jcsb]: title === '风险外链'})}>
				<div className={s.df_aic}>
					{title}
					<span className={s.num}>({tableData.length})</span>
					{/* <Tooltip
						placement="top"
						overlay={<span>{title === '坏链' ? '低危' : '高危'}</span>}
					>
						<span style={style}>
							<Icon grade={title === '坏链' ? 1 : 3} />
						</span>
					</Tooltip> */}
				</div>
				{title === '风险外链' && <div className='df aic jcfe'>
					<Select placeholder='风险外链类型'
						className={s.w160}
						value={[filter.type]}
						clearable
						onChange={({ selectedItem }) => setFilter({ ...filter, type: selectedItem[0]?.value || ''})}
						option={[
						{ label: '违规内容', value: 'keyword' },
						{ label: '风险域名', value: 'domain' },
						{ label: '未备案', value: 'icp' },
					]} />
					<Select className={cn('ml10 mr10', s.w160)} placeholder='威胁等级'
						value={[filter.level]}
						clearable
						onChange={({ selectedItem }) => setFilter({ ...filter, level: selectedItem[0]?.value || ''})}
						option={[
						{ label: '严重', value: '5' },
						{ label: '高危', value: '4' },
						{ label: '中危', value: '3' },
						{ label: '低危', value: '2' },
					]} />
					<Button className={'primary-btn'} onClick={() => setFilter({ type: '', level: '' })}>重置</Button>
				</div>}
			</div>
			{isModified ? (
				<>
					<Table
						loading={loading}
						rowSelection={notStatus ? null : rowSelection}
						columns={colum}
						data={tableData}
						className={cn(s.table)}
						pro
						empty={empty}
						scroll={tableData.length ? { y: '235px', x: 'unset' } : null}
					/>
					{!notStatus && <div>
						<IgnoreRiskConfirm className={'p0 mt5'}
							text='批量忽略'
							disabled={selectedRowKeys?.length === 0}
							data={{ warning_ids: selectedRowKeys, task_id: tableData[0]?.tid }} refresh={r_ => {
								refresh(r_)
								handleResetSelected()
							}} />
					</div>}
				</>
			) : (
				<Table
					columns={colum}
					data={tableData}
					pro
					loading={loading}
					empty={empty}
					scroll={tableData?.length ? { y: '235px', x: 'unset' } : null}
				/>
			)}
		</div>
	);
}

NewTable.propTypes = {
	className: PropTypes.string,
	title: PropTypes.string.isRequired,
	data: PropTypes.object,
	isModified: PropTypes.bool,
	taskId: PropTypes.string,
	refetch: PropTypes.func,
	cydEnabled: PropTypes.bool,
	linkType:PropTypes.string,
};
NewTable.defaultProps = {
	className: '',
	isModified: true,
	data: [],
};

export default NewTable;
